/**
 * 文章分类
 */
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;

var CategorySchema = new Schema({
            name: String,
            blogs: [{
                type: ObjectId,
                ref: 'Blog'
            }],
            remarks:String,
            meta: {
                createAt: { //创建时间
                    type: Date,
                    default: Date.now()
                },
                updateAt: { //更新时间
                    type: Date,
                    default: Date.now()
                }
            }

        }

        CategorySchema.pre = ('save', function(next) {
            var category = this;
            if (category.isNew) {
                category.meta.createAt = category.meta.updateAt = Date.now();
            } else {
                categorySchema.meta.updateAt = Date.now();
            }
        });

        CategorySchema.statics = {
            fetch: function(cb) {
                return this
                    .find({})
                    .sort('meta.updataAt')
                    .exec(cb)
            },
            fetchByAttr: function(value, cb) {
                return this
                    .find()
                    .sort('meta.createAt')
                    .exec(cb)
            },
            findOneByAttr: function(value, cb) {
                return this
                    .findOne(value)
                    .exec(cb)
            },
            top: function(pagesize, pageindex, cb) {
                return this
                    .find({})
                    .skip(pagesize * (pageindex - 1), cb)
                    .limit(pagesize)
                    .sort('meta.updateAt')
                    .exec(cb)
            }
        }


        module.exports = CategorySchema;
